%%%%%%%%%%%%%%
%%%%%%%%%%%%%%
% Data moments
%%%%%%%%%%%%%%
%%%%%%%%%%%%%%

[M_full,var_M_full,W_full,X_monthly,random_state]    ...
                                        = data_moments(root_folder,'baseline');

%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%
% Initialize (pars,Nu)
%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%

[pars,Nu]                               = setup_function([],random_state,'baseline');

%%%%%%%%%%%%
%%%%%%%%%%%%
% Estimate
%%%%%%%%%%%%
%%%%%%%%%%%%

k_target                                = 0.166;
xi_grid                                 = 0.00850;
verbose                                 = 0;
[output,SortResults,OutTable]           = estimate_k(k_target,pars,Nu,M_full,W_full,random_state,verbose,xi_grid); 

%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%
% Tables 6 and 7
%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%

diary([root_folder '/output/' 'tables/dummy.txt']);
setup_inputs.xi                         = output{1}.XiFinalAllPars(1);
setup_inputs.sigma                      = output{1}.XiFinalAllPars(2);
setup_inputs.S                          = output{1}.XiFinalAllPars(4);
setup_inputs.M_e                        = output{1}.XiFinalAllPars(5); 
setup_inputs.C                          = output{1}.XiFinalAllPars(6);
[pars,Nu]                               = setup_function(setup_inputs,random_state,'baseline');
verbose                                 = 1;
Nu.targeted_pars                        = {'S','C','k','sigma','M_e'};
Nu.Npars                                = numel(Nu.targeted_pars);
Nu.fixed_pars                           = setdiff(Nu.all_pars,Nu.targeted_pars);
diagnostics(pars,M_full,W_full,Nu,1);
diary off;

% Process output
ffs = [root_folder '/output/' 'tables/dummy.txt'];
str = fileread( ffs );
out = regexprep( str, '<\x2F?strong>', '' );
fid = fopen([root_folder '/output/' 'tables/Tables_6_and_7.txt'], 'wt');
fwrite(fid, out);
fclose(fid);
delete([root_folder '/output/' 'tables/dummy.txt']);

save([root_folder '/temp/output_from_estimation.mat']);
